//
//  SRSpeakingTestTableViewCell.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/4/20.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRSpeakingTestTableViewCell.h"
//#import "FZCircleProgressView.h"
#import <UITextView+Extras.h>

NSInteger const cMaxVisibleTextLenght = 80;

NSString *const kSRSpeakingTestTableViewCell = @"SRSpeakingTestTableViewCell";

@interface SRSpeakingTestTableViewCell ()

@property (weak, nonatomic) IBOutlet UIView *borderContentView;
@property (weak, nonatomic) IBOutlet UITextView *enTextView;
@property (weak, nonatomic) IBOutlet UITextView *chTextView;
@property (weak, nonatomic) IBOutlet UIView *controlView;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIButton *originPlayButton;
@property (weak, nonatomic) IBOutlet UIButton *centerOriginPlayButton;
@property (weak, nonatomic) IBOutlet UILabel *recordScoreLabel;

@property (weak, nonatomic) IBOutlet UIButton *recordButton;
@property (weak, nonatomic) IBOutlet UIButton *userRecordPlayButton;
@property (weak, nonatomic) IBOutlet UIButton *shareButton;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

//@property (strong, nonatomic) UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *enTextHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *controlHeightConstraint;

@property (assign, nonatomic) NSTimeInterval recorderDuration;
@property (strong, nonatomic) UITapGestureRecognizer* tapTextGesture;
@property (strong, nonatomic) UIView *selectionView;

@property (weak, nonatomic) IBOutlet UIImageView *scoreImageView;
@property (weak, nonatomic) IBOutlet UILabel *scoreLabel;


@end


@implementation SRSpeakingTestTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    self.selectedBackgroundView = nil;//[[UIView alloc] init];
//    self.selectedBackgroundView.backgroundColor = [UIColor clearColor];
    
    self.backgroundColor = [UIColor clearColor];
    self.contentView.backgroundColor = [UIColor clearColor];
    
    self.borderContentView.layer.masksToBounds = YES;
    self.borderContentView.layer.cornerRadius = 5;
    
    self.borderContentView.backgroundColor = css.color_5;
    self.enTextView.backgroundColor = self.chTextView.backgroundColor = [UIColor clearColor];
    self.enTextView.textColor = self.chTextView.textColor = css.color_6;
    self.enTextView.font = self.chTextView.font = css.fontOfH3;
    self.enTextView.contentInset = self.chTextView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.timeLabel.textColor = css.color_2;
    self.timeLabel.font = css.fontOfH5;

    self.controlView.layer.masksToBounds = YES;
    self.controlView.backgroundColor = [UIColor clearColor];
    
    CGFloat buttonCornerRadius = 45 / 2.0;
    self.originPlayButton.layer.masksToBounds = YES;
//    self.originPlayButton.layer.cornerRadius = buttonCornerRadius;
//    [self.originPlayButton setBackgroundImage:[UIImage imageWithColor:css.color_7] forState:UIControlStateNormal];
    
    self.recordButton.layer.masksToBounds = YES;
//    self.recordButton.layer.cornerRadius = 65 / 2.0;
//    [self.recordButton setBackgroundImage:[UIImage imageWithColor:css.color_7] forState:UIControlStateNormal];
	
    self.userRecordPlayButton.layer.masksToBounds = YES;
    self.userRecordPlayButton.layer.cornerRadius = buttonCornerRadius;
    [self.userRecordPlayButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHex:0x5CC323]] forState:UIControlStateNormal];
	[self.userRecordPlayButton setImage:[UIImage imageNamed:@"icon_userRecordPlay"] forState:UIControlStateNormal];
	self.recordScoreLabel.text = @"";
	
    self.shareButton.layer.masksToBounds = YES;
//    self.shareButton.layer.cornerRadius = buttonCornerRadius;
//    [self.shareButton setBackgroundImage:[UIImage imageWithColor:css.color_7] forState:UIControlStateNormal];
	
//    self.progressBgView.layer.masksToBounds = YES;
//    self.progressBgView.layer.cornerRadius = buttonCornerRadius;
    
//    self.progressView = [[UIProgressView alloc] init];
//    self.progressView.backgroundColor = [UIColor redColor];
    self.progressView.trackTintColor = css.color_7;
//    self.progressView.progressRingWidth = 45;
//    self.progressView.backgroundTintColor = css.color_4;
    self.progressView.progressTintColor = css.color_2;
    self.progressView.layer.masksToBounds = YES;
    self.progressView.layer.cornerRadius = 22.f;
    
//    [self.progressBgView addSubview:self.progressView];
//    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.leading.equalTo(self.progressBgView.mas_leading).offset(0);
//        make.trailing.equalTo(self.progressBgView.mas_trailing).offset(0);
//        make.top.equalTo(self.progressBgView);
//        make.bottom.equalTo(self.progressBgView);
//    }];
    
    self.progressView.hidden = YES;
    
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapTextViewAction:)];
    [self.borderContentView addGestureRecognizer:tap];
    self.tapTextGesture = tap;
    [self.tapTextGesture setEnabled:NO];
    
    self.selectionView = [[UIView alloc] init];
    self.selectionView.backgroundColor = [UIColor colorWithHex:0x5cc323 withAlpha:0.7];
    self.selectionView.hidden = YES;
    [self.borderContentView addSubview:self.selectionView];
    
    self.scoreLabel.textColor = css.color_4;
    self.scoreLabel.font = css.fontOfH5;
}

- (void)setIsRecording:(BOOL)isRecording {
    _isRecording = isRecording;
    
    if (isRecording) {
        self.progressView.hidden = NO;
//        self.userRecordPlayButton.hidden = YES;
//        self.shareButton.hidden = YES;
    } else {
        self.progressView.hidden = YES;
//        self.userRecordPlayButton.hidden = NO;
//        self.shareButton.hidden = NO;
		self.userRecordPlayButton.hidden = NO;
//		self.recordScoreLabel.hidden = NO;
		self.originPlayButton.hidden = NO;
		self.shareButton.hidden = NO;
		
		self.centerOriginPlayButton.hidden = YES;
    }
}

- (void)setScoreModel:(SREvaluationScoreModel * )scoreModel {
    self.model.scoreModel = scoreModel;
    if (scoreModel) {
        if (scoreModel.originScore && [scoreModel.originScore integerValue] > 0) {
            NSString *score = [NSString stringWithFormat:@"%@", scoreModel.originScore];
//            [self.userRecordPlayButton setTitle:score forState:UIControlStateNormal];
			self.recordScoreLabel.text = score;
            if ([score integerValue] >= 60) {
                [self.userRecordPlayButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHex:0x5CC323]] forState:UIControlStateNormal];
            } else {
                [self.userRecordPlayButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHex:0xfd4f1a]] forState:UIControlStateNormal];
            }
        } else {
//            [self.userRecordPlayButton setTitle:@"" forState:UIControlStateNormal];
			self.recordScoreLabel.text = @"";
        }
        
    } else {
//        [self.userRecordPlayButton setTitle:@"" forState:UIControlStateNormal];
		self.recordScoreLabel.text = @"";
    }
}

- (void)setTopScoreHidden:(BOOL)isHidden {
    self.scoreImageView.hidden = isHidden;
    self.scoreLabel.hidden = isHidden;
}

- (void)updateViewLayoutWithIsExpand:(BOOL)isExpand{
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];

    if (isExpand) {
        self.borderContentView.backgroundColor = css.color_5;
//        self.enTextView.backgroundColor = self.chTextView.backgroundColor = //css.color_5;
        self.enTextView.textColor = self.chTextView.textColor = css.color_6;
        self.enTextHeightConstraint.constant = MIN(self.model.enHeight, SCREEN_HEIGHT / 2.0);
        self.controlHeightConstraint.constant = 210;
        self.chTextView.text = self.model.track_genre;
//		self.userRecordPlayButton.hidden = !self.model.hasRecord;
//        self.shareButton.hidden = !self.model.hasRecord;
        self.tapTextGesture.enabled = YES;
		if (self.model.hasRecord) {
			self.userRecordPlayButton.hidden = NO;
			self.originPlayButton.hidden = NO;
			self.shareButton.hidden = NO;
			
			self.centerOriginPlayButton.hidden = YES;
		} else {
			self.userRecordPlayButton.hidden = YES;
			self.originPlayButton.hidden = YES;
			self.shareButton.hidden = YES;
			
			self.centerOriginPlayButton.hidden = NO;
		}
		
        [self setTopScoreHidden:YES];
    } else {
        
        if ([self.model.track_txt length] > cMaxVisibleTextLenght) {
            NSString *title = [self.model.track_txt substringWithRange:NSMakeRange(0, cMaxVisibleTextLenght)];
            self.enTextView.text = [NSString stringWithFormat:@"%@...", title];
        }
        
        self.enTextHeightConstraint.constant = 50;
        self.controlHeightConstraint.constant = 0;
        self.chTextView.text = nil;
        self.borderContentView.backgroundColor = css.color_1;
//        self.enTextView.backgroundColor = self.chTextView.backgroundColor = css.color_1;
//        self.enTextView.backgroundColor = self.chTextView.backgroundColor = [UIColor whiteColor];
        self.enTextView.textColor = self.chTextView.textColor = css.color_4;
        self.tapTextGesture.enabled = NO;
        
        [self hideSelectedView];
        
        if (self.model.scoreModel) {
            if (self.model.scoreModel.originScore && [self.model.scoreModel.originScore integerValue] > 0) {
                NSInteger score = [self.model.scoreModel.originScore integerValue];
                NSString *scoreString = [NSString stringWithFormat:@"%d", (int)score];
                
                self.scoreLabel.text = scoreString;
                if (score < 60) {
                    self.scoreImageView.image = [UIImage imageNamed:@"unpass"];
                } else {
                    self.scoreImageView.image = [UIImage imageNamed:@"pass"];
                }
                
                [self setTopScoreHidden:NO];
            } else {
                [self setTopScoreHidden:YES];
            }
        } else {
            [self setTopScoreHidden:YES];
        }
        
    }
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)updateCellInfo:(SRBookPageTrackItemModel *)model {
    if (!model) {
        return;
    }
    self.model = model;
    
    self.enTextView.text = model.track_txt;
    self.chTextView.text = model.track_genre;
    self.progressView.progress = 0;
    self.recorderDuration = [model.track_auend floatValue] - [model.track_austart floatValue];
    self.timeLabel.text = [NSString stringWithFormat:@"%.2fs", self.recorderDuration];
    
    if (model.scoreModel && model.scoreModel.originScore && [model.scoreModel.originScore integerValue] > 0) {
        NSString *score = [NSString stringWithFormat:@"%@", model.scoreModel.originScore];
//        [self.userRecordPlayButton setTitle:score forState:UIControlStateNormal];
		self.recordScoreLabel.text = score;
		
        if ([score integerValue] >= 60) {
            [self.userRecordPlayButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHex:0x5CC323]] forState:UIControlStateNormal];
        } else {
            [self.userRecordPlayButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHex:0xfd4f1a]] forState:UIControlStateNormal];
        }
    } else {
//        [self.userRecordPlayButton setTitle:@"" forState:UIControlStateNormal];
		self.recordScoreLabel.text = @"";
    }
    
    self.isExpand = model.isExpand;
    
    [self updateViewLayoutWithIsExpand:self.isExpand];
}

- (void)setProgress:(CGFloat)progress {
    [self.progressView setProgress:progress animated:YES];
}


#pragma mark - Event 

- (IBAction)onTouchOriginPlayButton:(id)sender {
    
    if (self.touchOriginPlayButtonBlock) {
        self.touchOriginPlayButtonBlock(self.model, sender);
    }
}

- (IBAction)onTouchRecordButton:(id)sender {
    
    self.progressView.progress = 0;
//    if (self.isRecording) {
//            //停止录音
//        self.isRecording = NO;
//    } else{
        self.isRecording = YES;
//    }
    if (self.touchRecodButtonBlock) {
        self.touchRecodButtonBlock(self.model, sender, self.isRecording, self.indexPath);
    }
}

- (IBAction)userRecordPlayButton:(id)sender {
    if (self.touchUserRecordPlayButtonBlock) {
        self.touchUserRecordPlayButtonBlock(self.model, sender);
    }
}

- (IBAction)onTouchShareButton:(id)sender {
    if (self.touchShareButtonBlock) {
        self.touchShareButtonBlock(self.model, sender);
    }
}

- (void)onTapTextViewAction:(UITapGestureRecognizer *)tgr {
    if (self.isExpand) {
        [self handleWordTap:tgr];
    } else {
        
    }
}

-(void)handleWordTap:(UITapGestureRecognizer*)tap{
    
    self.selectionView.alpha = 1;
    self.selectionView.hidden = NO;
    if(tap.state == UIGestureRecognizerStateRecognized){
        CGPoint tappedPoint = [tap locationInView:self.enTextView];
        if (tappedPoint.y < self.enTextView.contentOffset.y || tappedPoint.y > self.enTextView.contentOffset.y + self.enTextView.bounds.size.height)
        {
            [self hideSelectedView];
            return;
        }
        NSUInteger idx = [self.enTextView closestCharacterIndexToPoint:tappedPoint];
        UITextGranularity granularity =UITextGranularityWord;
        NSString *result =[self.enTextView substringWithGranularity:granularity atPoint:tappedPoint];
        if ([result  isKindOfClass:[NSNull  class]])
        {
            [self hideSelectedView];
            return;
        }else{
            if (result.length>0) {
                UIBezierPath* selectionInTextViewPath = [self.enTextView selectionPathWithGranularity:granularity atIndex:idx];
                [UIView animateWithDuration:.0001
                                 animations:^{
                                     CGRect newFrame =
                                     CGPathGetPathBoundingBox(selectionInTextViewPath.CGPath);
                                     self.selectionView.frame = [self.borderContentView convertRect:newFrame fromView:self.enTextView];
                                 }];
                NSDictionary *info = [@{} mutableCopy];
                [info setValue:result forKey:@"word"];
                NSString *str = result;
                int unichar = [str characterAtIndex:0];
                if( unichar > 0x4e00 && unichar < 0x9fff)
                {
                    self.selectionView.alpha =0;
                    [self hideSelectedView];
                }
                else{
                    
//                    [[NSNotificationCenter defaultCenter] postNotificationName:@"wordToTransNote" object:nil userInfo:info];
                    if (self.touchWordTranslateBlock) {
                        self.touchWordTranslateBlock(result);
                    }
                }
            }
        }
        
        NSString  *words = [NSString  stringWithFormat:@"%@",[self.enTextView substringWithGranularity:granularity atPoint:tappedPoint]];
        if ([words  isEqualToString:@"(null)"])
        {
            [self hideSelectedView];
            self.selectionView.alpha =0;
        }
            //        [[NSNotificationCenter defaultCenter] postNotificationName:@"HANDLETAPNOTI" object:self.recordModel];
    }
}

- (void)hideSelectedView {
    self.selectionView.frame = CGRectZero;
    self.selectionView.alpha = 1;
    
    if (self.hideWordTranslateBlock) {
        self.hideWordTranslateBlock();
    }
}

@end
